//
//  HDUtil.m
//  DooiooOnline
//
//  Created by koki on 14-11-6.
//  Copyright (c) 2014年 dooioo. All rights reserved.
//

#import "HDUtil.h"
#import <CommonCrypto/CommonHMAC.h>


@implementation HDUtil

//检查电话号码是否合法
+(BOOL)checkPhoneNumInput:(NSString *)number
{
    NSString * MOBILE = @"^[0-9]{8,20}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    BOOL res1 = [regextestmobile evaluateWithObject:number];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证手机
+(BOOL)checkMoblieNumber:(NSString *)number
{
    NSString * MOBILE = @"^1[3|4|5|8][0-9]\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    BOOL res1 = [regextestmobile evaluateWithObject:number];
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证姓名
+(BOOL)checkName:(NSString *)name
{
    NSString * Name = @"[a-zA-Z\u4e00-\u9fa5][a-zA-Z\u4e00-\u9fa5]+";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Name];
    BOOL res1 = [regextestmobile evaluateWithObject:name];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证身份证号
+(BOOL)checkIdCardNo:(NSString *)idCardNo
{
    NSString * IdCardNo = @"^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", IdCardNo];
    BOOL res1 = [regextestmobile evaluateWithObject:idCardNo];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证价格
+(BOOL)checkPrice:(NSString *)price
{
    NSString * Price = @"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Price];
    BOOL res1 = [regextestmobile evaluateWithObject:price];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证银行卡
+(BOOL)checkBankCardId:(NSString *)bankCardId
{
    NSString * BankCardId = @"^\\d{8,}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", BankCardId];
    BOOL res1 = [regextestmobile evaluateWithObject:bankCardId];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证密码
+(BOOL)checkPassword:(NSString *)password
{
    NSString * Password = @"[\\w\\W]{6,16}";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Password];
    BOOL res1 = [regextestmobile evaluateWithObject:password];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(NSString*)formatter:(NSString*) formattter FromeDate:(NSDate*)date
{
    NSString *returnValue;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormatter setDateFormat:formattter];
    returnValue = [dateFormatter stringFromDate:date];
    return returnValue;
}

+(BOOL)isValidateEmail:(NSString *)email
{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    return [emailTest evaluateWithObject:email];
}

+(NSString*)formatter:(NSString*) formattter FromTime:(double)time
{
    NSString *returnValue=[NSString string];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formattter];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time/1000];
    if (time==0)
    {
        date=[NSDate date];
    }
    returnValue = [dateFormatter stringFromDate:date];
    return returnValue;
}

//检查名字是否合法
+(BOOL)checkNameInput:(NSString *)number
{
    NSString * name = @"^([\u4E00-\u9FA5]+|[a-zA-Z]+)$";
    NSPredicate *regextestaccount = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", name];
    BOOL res1 = [regextestaccount evaluateWithObject:number];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}


//检查密码是否合法
+(BOOL)checkPasswordInput:(NSString *)password
{
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,100}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
}

//获取字符串的size
+(CGSize)getSizeWithText:(NSString*)text fontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    return size;
}

//获取字符串的size
+(CGSize)getSizeWithText:(NSString*)text font:(UIFont*)font
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: font}];
    return size;
}

+(CGSize)getSizeWithText:(NSString*)text boldfontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:fontSize]}];
    return size;
}

//创建指定字窜的Label
+(UILabel*)UILabelWithText:(NSString*)text boldFontSize:(int)fontSize
{
    
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    UILabel* Label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    Label.text=text;
    Label.backgroundColor=[UIColor clearColor];
    Label.font=[UIFont boldSystemFontOfSize:fontSize];
    return Label;
}

+(void)shakeAnimationOfView:(UIView*)view
{
    CGFloat rotation = 0.5;
    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"transform"];
    shake.duration = 0.13;
    shake.autoreverses = YES;
    shake.repeatCount  = 2;
    shake.removedOnCompletion = YES;
    shake.fromValue = [NSValue valueWithCATransform3D:CATransform3DRotate(view.layer.transform,-rotation, 0.0 ,0.0 ,1.0)];
    shake.toValue   = [NSValue valueWithCATransform3D:CATransform3DRotate(view.layer.transform, rotation, 0.0 ,0.0 ,1.0)];
    [view.layer addAnimation:shake forKey:@"shakeAnimation"];
}

+(UIImage*)getSnapshotFromView:(UIView*)view
{
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 1);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

+(UIImage*)getSnapshotFromView:(UIView*)view rect:(CGRect)rect
{
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 1);
    [view drawViewHierarchyInRect:rect afterScreenUpdates:NO];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

+(void)addShoppingAnimation:(UIImageView*)imageView PointArray:(NSArray*)pointAarray delegate:(id)delegate
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    NSValue* valueTemp=pointAarray[0];
    CGPoint startPoint = [valueTemp CGPointValue];
    [path moveToPoint:startPoint];
    
    valueTemp=pointAarray[1];
    CGPoint centerPoint = [valueTemp CGPointValue];
    valueTemp=pointAarray[2];
    CGPoint endpoint = [valueTemp CGPointValue];
    [path addQuadCurveToPoint:endpoint controlPoint:centerPoint];
    
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
    animation.duration = 0.6;
    animation.delegate = delegate;
    [imageView.layer addAnimation:animation forKey:nil];
    
    CAKeyframeAnimation *animation1=[CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation1.duration = 0.6;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1,0.1,0.1)]];
    animation1.values = values;
    [imageView.layer addAnimation:animation1 forKey:nil];
    
    CABasicAnimation *opAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opAnim.duration = 0.6;
    opAnim.fromValue = [NSNumber numberWithFloat:0.1];
    opAnim.toValue= [NSNumber numberWithFloat:1.0];
    [imageView.layer addAnimation:opAnim forKey:nil];
}


//按宽度获取图片合适尺寸
+ (CGSize)newSizeByOriginalSize:(CGSize)oldSize maxSize:(CGSize)mSize newWidth:(float)newWidth
{
    if (oldSize.width <= 0 || oldSize.height <= 0)
    {
        return CGSizeZero;
    }
    
    CGSize newSize = CGSizeZero;
    if (oldSize.width > mSize.width || oldSize.height > mSize.height)
    {
        //按比例计算尺寸
        float bs = newWidth / oldSize.width;;
        float newHeight = oldSize.height * bs;
        newSize = CGSizeMake(mSize.width, newHeight);
    }
    else
    {
        
        newSize = oldSize;
    }
    return newSize;
}

//获取字符窜大小
+(CGSize)sizeWithString:(NSString*) string  font:(UIFont*)font size:(CGSize)size
{
    
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:2];
  
    NSDictionary *attribute = @{NSFontAttributeName: font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize textSize = [string boundingRectWithSize:size
                                           options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;
    return textSize;
}

//获取字符窜大小
+(CGSize)sizeWithString:(NSString*) string  attribute:(NSDictionary*)attribute size:(CGSize)size
{
    CGSize textSize = [string boundingRectWithSize:size
                                           options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;
    return textSize;
}

//获取NSAttributed字符窜大小
+(CGSize)sizeWithString:(NSAttributedString*) attrStr size:(CGSize)size
{
    CGSize textSize = [attrStr boundingRectWithSize:size
                                            options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                            context:nil].size;
    return textSize;
}

//创建指定字窜的Label
+(UILabel*)UILabelWithText:(NSString*)text fontSize:(int)fontSize
{
    CGSize size=[self getAttributeSizeWithText:text fontSize:fontSize];
    UILabel* Label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    Label.text=text;
    Label.backgroundColor=[UIColor clearColor];
    Label.font=[UIFont systemFontOfSize:fontSize];
    return Label;
}

+ (CGSize) getAttributeSizeWithText:(NSString *)text fontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    if (isIos7Later) {
        size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    }else{
        NSAttributedString *attributeSting = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
        size = [attributeSting size];
    }
    return size;
}

+(float)heightForTextViewSize:(CGSize)size  WithText: (NSString *) strText font:(UIFont*)font
{
    float fPadding = 16.0;
    CGSize constraint = CGSizeMake(size.width - fPadding, CGFLOAT_MAX);
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    
    NSDictionary *attribute = @{NSFontAttributeName: font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize newSize = [strText boundingRectWithSize:constraint
                                           options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;

    newSize.height+=16.0;
    return newSize.height;
}


+(UIButton*)buttonWithTitle:(NSString*)title frame:(CGRect)rect
{
    UIButton* button=[UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:title forState:UIControlStateNormal];
     button.frame=rect;
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    return button;
}
//MD5加密
+(NSString *)MD5:(NSString *)str{
    //32位MD5小写
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+(int)calculateDaysFromDate:(NSDate*)date
{
    NSString* str=[HDUtil formatter:@"yyyy-MM-dd" FromeDate:date];
    str=[str stringByAppendingString:@" 0:0:0"];
    date=[HDUtil getDateFromeString:str];
    NSUInteger unitFlags =NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit;
    NSCalendar *cal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate* today=[NSDate date];
    
    NSDateComponents *comps = [cal components:unitFlags fromDate:date toDate:today options:0];
    NSInteger days=[comps day];
    NSInteger years=[comps year];
    NSInteger months=[comps month];
    days=(days+months*30+years*365);
    return (int)days;
}


+(NSDate*)getDateFromeString:(NSString*)str
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:str];
    if(date==nil)
        date=[NSDate date];
    return date;
}

+(NSString*)formatter:(NSString*) formattter FromeDateStr:(NSString*)str
{
    NSString *returnValue=[NSString string];
    if(![str isKindOfClass:[NSString class]])
    {
        return returnValue;
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:str];
    if(date==nil)
    {
        return returnValue;
    }
    [dateFormatter setDateFormat:formattter];
    returnValue = [dateFormatter stringFromDate:date];
    return returnValue;
}



+(void)hidenKeyBoard
{
    [[[UIApplication sharedApplication]keyWindow] endEditing:YES];
}



+(NSString*)check:(NSObject*)data
{
    NSString* string=@"";
    if ([data isKindOfClass:[NSString class]])
    {
        string=(NSString*)data;
    }
    else if ([data isKindOfClass:[NSNumber class]])
    {
        string=[(NSNumber*)data stringValue];
    }
    return string;
}

+(NSData*)checkData:(NSData*)value
{
    NSData* data=[NSData data];
    if([value isKindOfClass:[NSData class]])
    {
        data=(NSData*)value;
    }
    return data;
}

+(NSNumber*)checkNumber:(NSNumber*)num
{
    NSNumber* number=[NSNumber numberWithInt:0];
    if([num isKindOfClass:[NSNumber class]])
    {
        number=(NSNumber*)num;
    }
    return number;
}


+(NSArray*)checkNilArray:(NSArray*)array
{
    NSMutableArray* destArray=[[NSMutableArray alloc] initWithCapacity:0];
    if (array!=nil&&([array isKindOfClass:[NSArray class]]||[array isKindOfClass:[NSMutableArray class]]))
    {
        return array;
    }
    
    return destArray;
}


+(NSArray*)checkArray:(NSArray*)array
{
    NSMutableArray* destArray=[[NSMutableArray alloc] initWithCapacity:0];
    for (NSString* item in array)
    {
        NSString* str=[HDUtil clearSpaces:item];
        if(str.length)
        {
            [destArray addObject:str];
        }
    }
    return destArray;
}




+(NSString *)currentVersion
{
     return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}



+(NSString*)clearSpaces:(NSString*)str
{
    str=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    return str;
}

+(NSString*)strNumberRound:(NSObject*)data
{
    if ([data isKindOfClass:[NSString class]])
    {
        return [NSString stringWithFormat:@"%d",(int)round([((NSString*)data) doubleValue])];
    }
    else if ([data isKindOfClass:[NSNumber class]])
    {
        return [NSString stringWithFormat:@"%d",(int)round([((NSNumber*)data) doubleValue])];
    }
    return @"-";
}

+(NSString*)numberFormatterDecimalStyle:(NSNumber*)data
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    return [formatter stringFromNumber: data];
}

+(BOOL)call:(NSString *)phoneNumber
{
    NSLog(@"%@",phoneNumber);
    phoneNumber=[HDUtil clearSpaces:phoneNumber];
    return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
}


+(void)showTipAlertWithMsg:(NSString*)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performBlock:^
     {
         [alert dismissWithClickedButtonIndex:0 animated:YES];
     }
    afterDelay:1.2];
}

//删除本地数据库图片缓存
+(void)deleteImageCache
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ImageCache" inManagedObjectContext:rootContext];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSArray *fetchedObjects = [rootContext executeFetchRequest:fetchRequest error:&error];
    for (ImageCache *item in fetchedObjects)
    {
        [rootContext deleteObject:item];
    }
    if(![rootContext save:&error])
    {
        NSLog(@"%@",[error localizedDescription]);
    }
}

@end
























